import java.util.Arrays;

/**
 * @author guanhao 观浩
 * @version 1.0.0.0
 * @createTime 2023/2/19 10:35 AM
 * @company Michale Squirrel
 * @link
 * @description
 */
public class LeetCode6362 {

    public int[][] mergeArrays(int[][] nums1, int[][] nums2) {
        int leftIndex = 0;
        int rightIndex = 0;

        int[][] help = new int[nums1.length+nums2.length][2];
        int helpIndex = 0;
        int totalCount = 0;
        while (leftIndex < nums1.length && rightIndex < nums2.length) {
            if (nums1[leftIndex][0] < nums2[rightIndex][0]) {
                help[helpIndex] = nums1[leftIndex];
                helpIndex++;
                leftIndex++;
            } else if (nums1[leftIndex][0] > nums2[rightIndex][0]) {
                help[helpIndex] = nums2[rightIndex];
                helpIndex++;
                rightIndex++;
            } else {
                help[helpIndex][0] = nums1[leftIndex][0];
                help[helpIndex][1] = nums1[leftIndex][1]+ nums2[rightIndex][1];
                helpIndex++;
                leftIndex++;
                rightIndex++;
            }
            totalCount++;
        }

        while (leftIndex < nums1.length) {
            help[helpIndex] = nums1[leftIndex];
            helpIndex++;
            leftIndex++;
            totalCount++;
        }

        while (rightIndex < nums2.length) {
            help[helpIndex] = nums2[rightIndex];
            helpIndex++;
            rightIndex++;
            totalCount++;
        }
        int[][] result = new int[totalCount][2];

        for (int i = 0; i < result.length; i++) {
            result[i] = help[i];
        }
        return result;

    }


    public static void main(String[] args) {
        LeetCode6362 leetCode6359 = new LeetCode6362();

//        示例 1：
//
//        输入：nums1 = [[1,2],[2,3],[4,5]], nums2 = [[1,4],[3,2],[4,1]]
//        输出：[[1,6],[2,3],[3,2],[4,6]]
//        解释：结果数组中包含以下元素：
//        - id = 1 ，对应的值等于 2 + 4 = 6 。
//        - id = 2 ，对应的值等于 3 。
//        - id = 3 ，对应的值等于 2 。
//        - id = 4 ，对应的值等于5 + 1 = 6 。
//        示例 2：
//
//        输入：nums1 = [[2,4],[3,6],[5,5]], nums2 = [[1,3],[4,3]]
//        输出：[[1,3],[2,4],[3,6],[4,3],[5,5]]
//        解释：不存在共同 id ，在结果数组中只需要包含每个 id 和其对应的值。

        int[][] nums1 = new int[][]{{1,2},{2,3},{4,5}};
        int[][] nums2 = new int[][]{{1,4},{3,2},{4,1}};

        int[][] result = leetCode6359.mergeArrays(nums1, nums2);
        for (int i = 0; i < result.length ; i++) {
            System.out.println(Arrays.toString(result[i]));
        }

        System.out.println("========================");

        int[][] nums3 = new int[][]{{2,4},{3,6},{5,5}};
        int[][] nums4 = new int[][]{{1,3},{4,3}};

        int[][] result2 = leetCode6359.mergeArrays(nums3, nums4);
        for (int i = 0; i < result2.length ; i++) {
            System.out.println(Arrays.toString(result2[i]));
        }

    }
}
